package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

@RestController
@RequestMapping("/mobile/setmeal")
@Slf4j
public class SetMealController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private SetMealService setMealService;

    /**
     * 查询套餐
     * @return
     */
    @GetMapping("/getSetmeal")
    public Result getSetmeal(){
        //连接redis
        Jedis jedis = jedisPool.getResource();
        //获取redis中数据
        String restList = jedis.get("list");

        if (!StringUtils.isEmpty(restList)){
            //数据存在则将数据转成集合并返回前端
            System.out.println("11111 = " + 11111);
            List<Setmeal> list = JSON.parseArray(restList, Setmeal.class);
            return new Result(true ,MessageConst.ACTION_SUCCESS,list);
        }
        //数据不存在去mysql数据库查询
        System.out.println("2222 = " + 2222);
        List<Setmeal> list = setMealService.findAll();
        //将查询的数据转成字符串存入redis
        //并返回数据到前端
        jedis.set("list",JSON.toJSON(list).toString());
        return new Result(true, MessageConst.ACTION_SUCCESS,list);
    }
    @GetMapping("/findById")
    public Result findById(Integer id){
        //rpc调用查询数据
        Setmeal setmeal = setMealService.findById(id);
        //返回
        return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
    }
}
